package com.yang.core.service;

import com.yang.service.api.UserService;
import com.yang.core.dao.UserRepository;
import com.yang.core.model.User;
import com.yang.service.model.vo.UserVO;
import com.zhy.base.tools.beans.BeanMapper;
import com.zhy.base.tools.em.YesOrNo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Column;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * Created by xin7k
 * Date: 2019/12/16 0016
 */
@Slf4j
@RestController
@RequestMapping("user")
@Api(tags = "用户操作API", description = "user")
public class UserServiceImpl implements UserService {


    private final String defaultPwd = "123456";

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private BeanMapper beanMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;



    @ApiOperation("通过微信注册或者登录")
    @ApiImplicitParam(name = "code", value = "微信授权码", required = true)
    @PostMapping("{openId}")
    @Override
    public UserVO saveWeChatUser(@PathVariable(value = "openId") String openId) {
        /*
         * 1. 判断openId有无登录
         * 2. 新增用户
         */
        User user = new User().setOpenId(openId);
        //此处用find 避免重复注册
        Optional<User> optional = userRepository.findOne(Example.of(user));
        if(optional.isPresent()){
            user = optional.get();
        } else {
            //补全User信息
            user.setUserName(openId);
            user.setPassword(passwordEncoder.encode(defaultPwd));
            user.setEnable(YesOrNo.YES.getCode());
            userRepository.save(user);
        }
        return beanMapper.map(user, UserVO.class);


//        //甭看了   就是url都没有搞对
//        //你的这些命名哟， wx  s
//        //feign rpc api url is:  @PostMapping("user/{openId}")
//        //but you here url is：none   莫得url直接
//        //  加上url试下 ！！！！
//        log.info("前端获取的openId：" + openId);
//        //检查数据库中是否存在该OpenId
//        User user = new User();
//        user.setOpenId(openId);
//        //判断是否存在
//        //启动起来  进入断点 我再来
//        Optional<User> optional = userRepository.findOne(Example.of(user));
//        if(optional.isPresent()){
//            user = optional.get();
//            log.info("数据库获取的User：" + user.toString());
//            log.info("数据库获取的User：" + user.getId());
//            //beanMapper is null
//            //user only id and openId filed has value
//            //ai  空指针异常啊  ！！！！   你要回debug啊    查看变量值  分析问题  debugger windows    variables tab  is  变量值预览窗口
//            //欧克了
//            return beanMapper.map(user, UserVO.class);
//        }else{
//            user.setCreateTime(LocalDateTime.now());
//            user.setEnable(0);
//            userRepository.save(user);
//            return beanMapper.map(user,UserVO.class);
//        }
    }


    @ApiOperation("根据用户名字查找用户信息")
    @ApiImplicitParam(name = "userName", value = "用户名", required = true)
    @GetMapping("username/{userName}")
    @Override
    public UserVO findByUserName(@PathVariable("userName") String userName) {
        User user = new User();
        user.setUserName(userName);
        user.setEnable(YesOrNo.YES.getCode());
        //此处用select 判断用户是否被删除（用户违规等操作后会被删除或者封掉，但是不可重新注册，只能等解封）
        Optional<User> optional = userRepository.selectOne(Example.of(user));
        return optional.map(value -> beanMapper.map(value, UserVO.class)).orElse(null);
    }

    @ApiOperation("根据用户id用户信息")
    @ApiImplicitParam(name = "userId", value = "用户Id", required = true)
    @GetMapping("{userId}")
    @Override
    public UserVO getUserInfo(@PathVariable("userId") String userId) {
        User user = new User();
        user.setId(userId);
        Example<User> userExample = Example.of(user);
        Optional<User> one = userRepository.findOne(userExample);
        if(one.isPresent()){
            return beanMapper.map(one.get(),UserVO.class);
        }
        return null;
    }

}
